﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Reflection;
using System.Text;
using System.Web.UI;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Entities;
using VitCode.Castle.Helper;
using VitCode.Castle.Management;
using VitCode.Web.UI;
using VitCode.Web.UI.WebControls;

namespace AMS.Web.BackStageManagement
{
    public partial class UserList : Page
    {
        private BaseDataManager m_Acc = new BaseDataManager();
         
        private  string sql = " SELECT a.Id,a.Code,a.Name,a.Mobile,a.Email,a.Number,b.Name UserGroup  FROM  Frame_User a  left outer join Frame_UserGroup b on a.UserGroupId =b.Id ";
        
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>");
            ListGridInfo.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindList);
            if (Request.Cookies["Code"] == null)
            {
                Response.Redirect("../Default.aspx");
            }
            if (!IsPostBack)
            {
                ListGridInfo.BindGrid();
            }
            if (Session["RoleUserWinClose"] != null && Session["RoleUserWinClose"].ToString() == "Closed")
            {
                Session["RoleUserWinClose"] = null;
                ListGridInfo.BindGrid();
            }
           
             
       }


        private object BindList()
        {
            DataTable dt = m_Acc.GetDataTableBySql(sql);
            dt.Columns.Add("Role", typeof(string));
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string strRole = "";
                    string strUserId = dt.Rows[i]["id"].ToString();
                    string sqlStr =
                        "select a.Name from  Frame_Role  a join Frame_User_Role b on a.Id = b.RoleId join Frame_User c on c.id = b.UserId  where c.Id='" + strUserId + "'";

                    DataTable dt2 = new DataTable();
                    dt2 = m_Acc.GetDataTableBySql(sqlStr);
                    if (dt2.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt2.Rows.Count; j++)
                        {
                            strRole += dt2.Rows[j][0].ToString() + ",";
                        }
                        strRole = strRole.Substring(0, strRole.Length - 1);
                        dt.Rows[i]["Role"] = strRole;
                    }
                }
            }
            if (dt.Rows.Count > 0)
            {
                btnRealDelete.Enabled = true;
                btn_UserRoleAll.Enabled = true;
            }
            return dt;

        }

        protected void btnRealDelete_Click(object sender, EventArgs e)
        {
 

            string strDelVal = ListGridInfo.GetSelectedItem(1);
            if (string.IsNullOrEmpty(strDelVal.Trim()))
            {
                Alert.MessageBox("请选择要删除的用户!");
                return;
            }
            string[] strDel = strDelVal.Split(',');
            int iDeleteCount = 0;
            for (int i = 0; i < strDel.Length; i++)
            {
                if (!string.IsNullOrEmpty(strDel[i]))
                {
                    var castle = new CastleAccess();
                    if (castle.CheckIsAdmin(strDel[i]))
                    {
                        IList objList = m_Acc.GetObjectList(new User().GetType().Name, "Id", strDel[i]);
                        if (objList != null && objList.Count > 0)
                        {
                            var currentUser = (User)objList[0];
                            var strName = currentUser.Name;

                            Alert.MessageBox(strName + "为系统管理员，不能删除!");
                            return;
                        }
                    }
                }
                if (m_Acc.DeleteObjById(new User(), strDel[i]))
                    iDeleteCount++;
               

            }
            Alert.MessageBox("有" + iDeleteCount + "条记录被成功删除!");
            ListGridInfo.BindGrid();
            
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            const string strLink = "UserEdit.aspx";
            var win = new Window(Page, "用户新增")
            {
                 Height = 300,
                 Width = 560,
                Scrollbars = true,
                Status = true,
                Name = "用户新增"
            };
            win.ShowModalDialog(strLink, new[] { "hdCheckInfo" });
        }

        /// <summary>
        /// 批量设置用户的角色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button_UserGroupRole_Click(object sender, EventArgs e)
        {
            string sCheck = ListGridInfo.GetSelectedItem(1);
            if (string.IsNullOrEmpty(sCheck))
            {
                Alert.MessageBox("未选择用户！");
                return;

            }

            Response.Cookies["sCheck"].Value = sCheck; //页面间调用
            Response.Redirect("RolesUpdateAll.aspx", false);
        }

        protected void ListGridInfo_OnGridItemSelect(object sender, PaginationGridItemSelectArgs e)
        {
              string key = e.LastClickColumnIndex;
              string val = e.SelectedDataKeyValue;
              if (key == "2")
              {
                  
                  var win = new Window(Page, "用户修改")
                  {
                      Height = 300,
                      Width = 560,
                      Scrollbars = true,
                      Status = true,
                      Name = "用户修改"
                  };
                  win.ShowModalDialog("UserEdit.aspx?&Id=" + val, new [] { "hdCheckInfo" });
              }
              else
              {
                   var win = new Window(Page, "密码修改")
                          {
                              Height = 240,
                              Width = 520,
                              Scrollbars = true,
                              Status = true,
                              Name = "密码修改"
                          };
                   win.ShowModalDialog("PassUpdate.aspx?&Id=" + val, new [] { "hdCheckInfo" });
              }
            
           
        }

        protected void btnQuery_Click1(object sender, EventArgs e)
        {
            sql = " SELECT a.Id,a.Code,a.Name,a.Mobile,a.Email,a.Number,b.Name UserGroup  FROM  Frame_User a  left outer join Frame_UserGroup b on a.UserGroupId =b.Id ";
            if (ddlCondition.SelectedItem.Text != "" && txtValue.Text.Trim().Length > 0)
            {

                if (rbtAmount.Checked)
                    sql += "  where " + ddlCondition.SelectedItem.Value + " = '" + txtValue.Text.Trim() + "'";
                else sql += "  where " + ddlCondition.SelectedItem.Value + " like '%" + txtValue.Text.Trim() + "%'";


            }
            sql += " order by a.Code desc";
            ListGridInfo.DataSourceDelegate = new PaginationGrid.GridDataSourceDelegate(BindList);
            ListGridInfo.BindGrid();
        }
    }
}